﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using TomatoClock.Models;
using TomatoClock.Services;
using TomatoClock.Utilities;
using TomatoClock.ViewModels;

namespace TomatoClock.Views
{
    public partial class TomatoTimerControl : UserControl
    {
        private MainViewModel viewModel;
        private PomodoroTimer pomodoroTimer;
        private PomodoroTask currentTask;
        private IProcessMonitor processMonitor;

        // 事件声明
        public event Action TimerFinished;

        public TomatoTimerControl(MainViewModel viewModel, PomodoroTask task, List<string> disallowedProcesses)
        {
            InitializeComponent();
            this.viewModel = viewModel;
            currentTask = task;
            this.Dock = DockStyle.Fill;
            pomodoroTimer = new PomodoroTimer();
            processMonitor = new ProcessMonitor(disallowedProcesses);

            pomodoroTimer.TimeChanged += PomodoroTimer_TimeChanged;
            pomodoroTimer.TimerFinished += PomodoroTimer_TimerFinished;
            processMonitor.DisallowedProcessDetected += ProcessMonitor_DisallowedProcessDetected;

            InitializeTask();
        }

        private void InitializeTask()
        {
            taskNameLabel.Text = currentTask.Name;
            timeLabel.Text = $"{currentTask.Duration:D2}:00"; // Set initial time display
        }

        private void PomodoroTimer_TimeChanged(int timeLeft)
        {
            if (currentTask != null)
            {
                currentTask.TimeLeft = timeLeft;
            }

            timeLabel.Invoke((MethodInvoker)delegate
            {
                timeLabel.Text = $"{timeLeft / 60:D2}:{timeLeft % 60:D2}";
            });
        }

        private void PomodoroTimer_TimerFinished()
        {
            if (currentTask != null)
            {
                currentTask.IsCompleted = true;
                currentTask.EndTime = DateTime.Now;
                viewModel.CompleteTask(currentTask); // Save completed task
            }

            MessageBox.Show("Time's up!");
            StopMonitoring();
            startResumeButton.Enabled = true;
            pauseButton.Enabled = false;
            stopButton.Enabled = false;
            timeLabel.Text = $"{currentTask.Duration:D2}:00"; // Reset time label to default
            // 触发事件
            TimerFinished?.Invoke();
            ReturnToTimerSetter();
        }

        private void ProcessMonitor_DisallowedProcessDetected(string processName)
        {
            Invoke((MethodInvoker)delegate
            {
                MessageBox.Show($"检测到不允许的程序: {processName}， 番茄钟已停止.");
                stopButton_Click(this, EventArgs.Empty); // Stop the timer
                currentTask.IsCompleted = false;
                currentTask.EndTime = DateTime.Now;
                currentTask.Note = $"检测到不允许的程序: {processName}";
                viewModel.StopTask(currentTask); // Save stopped task with reason
            });
        }

        private void StartMonitoring()
        {
            processMonitor.StartMonitoring();
        }

        private void StopMonitoring()
        {
            processMonitor.StopMonitoring();
        }

        private void startResumeButton_Click(object sender, EventArgs e)
        {
            if (!currentTask.IsPaused&& (!pomodoroTimer.IsRunning()) ) {
                // 开始任务逻辑
                pomodoroTimer.Start(currentTask.Duration * 60); // Convert minutes to seconds
                startResumeButton.Enabled = false;
                pauseButton.Enabled = true;
                stopButton.Enabled = true;
                StartMonitoring(); // Start process monitoring
            }
            else
            {
                pomodoroTimer.Resume();
                startResumeButton.Enabled=false;
                pauseButton.Enabled = true;
            }
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            // 停止任务逻辑
            pomodoroTimer.Stop();
            StopMonitoring(); // Stop process monitoring

            if (currentTask != null)
            {
                currentTask.IsCompleted = false;
                currentTask.EndTime = DateTime.Now;
                viewModel.StopTask(currentTask); // Save stopped task
            }

            ReturnToTimerSetter();

            startResumeButton.Enabled = true;
            pauseButton.Enabled = false;
            stopButton.Enabled = false;
            TimerFinished?.Invoke();
        }

        private void pauseButton_Click(object sender, EventArgs e)
        {
            pomodoroTimer.Pause();

            if (currentTask != null)
            {
                currentTask.IsPaused = true;
            }

            pauseButton.Enabled = false;
            startResumeButton.Enabled = true;
        }

        private void resumeButton_Click(object sender, EventArgs e)
        {
            
        }

        private void ReturnToTimerSetter()
        {
            // 查找包含当前控件的窗体
            Form parentForm = this.FindForm();

            // 确保找到的窗体是 MainForm
            if (parentForm is MainForm mainForm)
            {
                // 调用 ShowPage 方法来显示 TomatoTimerSetterControl
                mainForm.ShowTimerPage(new TomatoTimerSetterControl(viewModel));
            }
        }
    }
}
